﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ComponentModel;
using System.Threading;

namespace NHTrace
{
  public class GridMessageRenderer : IMessageRenderer
  {
    private DataGridView _grid;

    public GridMessageRenderer(DataGridView grid)
    {
      _grid = grid;
      _grid.AutoGenerateColumns = true;
      _grid.ColumnHeadersVisible = false;
      _grid.RowHeadersVisible = false;
    }

    private bool firstRender = true;

    public void Render(IList<string> messages)
    {
      var bindableList = from m in messages select new { Message = m };

      _grid.Parent.BeginInvoke((ThreadStart)delegate()
      {
        _grid.DataSource = bindableList.ToList();

        if (firstRender)
        {
          _grid.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
          firstRender = false;
        }

        if (_grid.Rows.Count > 0)
          _grid.CurrentCell = _grid[0, _grid.Rows.Count - 1];
      });
    }
  }
}
